{% extends "base.html" %}

{% block title %}首页 - 生活助手{% endblock %}

{% block content %}
<div class="page-header">
    <h1><i class="bi bi-house-door"></i> 欢迎使用生活助手</h1>
    <p class="text-muted">您的个人效率管理中心</p>
</div>

<!-- 统计卡片区域 -->
<div class="row mb-4">
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="stats-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <i class="bi bi-check-square fs-1"></i>
            <h3 id="todo-count">0</h3>
            <p>待完成任务</p>
            <small id="todo-detail" class="text-white-50">加载中...</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="stats-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
            <i class="bi bi-trophy fs-1"></i>
            <h3 id="goal-count">0</h3>
            <p>进行中的目标</p>
            <small id="goal-detail" class="text-white-50">加载中...</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="stats-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
            <i class="bi bi-calendar-event fs-1"></i>
            <h3 id="event-count">0</h3>
            <p>今日日程</p>
            <small id="event-detail" class="text-white-50">加载中...</small>
        </div>
    </div>
    <div class="col-lg-3 col-md-6 mb-3">
        <div class="stats-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
            <i class="bi bi-heart-pulse fs-1"></i>
            <h3 id="habit-count">0</h3>
            <p>习惯打卡</p>
            <small id="habit-detail" class="text-white-50">加载中...</small>
        </div>
    </div>
</div>

<!-- 今日概览 -->
<div class="row mt-4">
    <div class="col-md-4 mb-3">
        <div class="card custom-card clickable-card" data-href="{{ url_for('todo.list_todos') }}">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="bi bi-list-check"></i> 今日待办</h5>
            </div>
            <div class="card-body" id="today-todos" style="max-height: 300px; overflow-y: auto;">
                <p class="text-muted text-center">加载中...</p>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 mb-3">
        <div class="card custom-card clickable-card" data-href="{{ url_for('health.list_habits') }}">
            <div class="card-header bg-danger text-white">
                <h5 class="mb-0"><i class="bi bi-heart-pulse"></i> 习惯打卡</h5>
            </div>
            <div class="card-body" id="today-habits" style="max-height: 300px; overflow-y: auto;">
                <p class="text-muted text-center">加载中...</p>
            </div>
        </div>
    </div>
    
    <div class="col-md-4 mb-3">
        <div class="card custom-card clickable-card" data-href="{{ url_for('schedule.calendar') }}">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="bi bi-calendar-day"></i> 今日日程</h5>
            </div>
            <div class="card-body" id="today-events" style="max-height: 300px; overflow-y: auto;">
                <p class="text-muted text-center">加载中...</p>
            </div>
        </div>
    </div>
</div>

<!-- 目标进度概览 -->
<div class="row mt-4">
    <div class="col-12">
        <div class="card custom-card clickable-card" data-href="{{ url_for('goal.list_goals') }}">
            <div class="card-header" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
                <h5 class="mb-0"><i class="bi bi-trophy"></i> 进行中的目标</h5>
            </div>
            <div class="card-body" id="active-goals">
                <p class="text-muted text-center">加载中...</p>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 页面加载完成后获取统计数据
document.addEventListener('DOMContentLoaded', function() {
    // 为可点击卡片添加点击事件
    document.querySelectorAll('.clickable-card[data-href]').forEach(card => {
        card.addEventListener('click', function() {
            window.location.href = this.getAttribute('data-href');
        });
    });
    
    // 获取待办统计
    fetch('/todo/api/stats')
        .then(response => response.json())
        .then(data => {
            document.getElementById('todo-count').textContent = data.pending_count || 0;
            document.getElementById('todo-detail').textContent = `今日到期: ${data.today_deadline || 0}`;  // 修复：使用正确的字段名
        })
        .catch(error => console.error('Error:', error));
    
    // 获取目标统计
    fetch('/goal/api/stats')
        .then(response => response.json())
        .then(data => {
            document.getElementById('goal-count').textContent = data.active_count || 0;
            document.getElementById('goal-detail').textContent = `已完成: ${data.completed || 0}`;
        })
        .catch(error => console.error('Error:', error));
    
    // 获取日程统计
    fetch('/schedule/api/today-events')
        .then(response => response.json())
        .then(data => {
            document.getElementById('event-count').textContent = data.count || 0;
            document.getElementById('event-detail').textContent = `本周: ${data.week_count || 0}`;
            
            // 显示今日日程
            const eventsContainer = document.getElementById('today-events');
            if (data.events && data.events.length > 0) {
                const displayEvents = data.events.slice(0, 3);  // 最多显示3条
                const remainingCount = data.events.length - 3;
                
                eventsContainer.innerHTML = displayEvents.map(event => `
                    <div class="mb-2 border-bottom pb-2">
                        <strong>${event.title}</strong><br>
                        <small class="text-muted"><i class="bi bi-clock"></i> ${event.start_time}</small>
                    </div>
                `).join('') + (remainingCount > 0 ? `
                    <div class="text-center mt-2">
                        <small class="text-muted">还有 ${remainingCount} 个事件...</small>
                    </div>
                ` : '');
            } else {
                eventsContainer.innerHTML = '<p class="text-muted text-center">今日暂无日程</p>';
            }
        })
        .catch(error => console.error('Error:', error));
    
    // 获取健康习惯统计
    fetch('/health/api/dashboard')
        .then(response => response.json())
        .then(data => {
            const checkedCount = data.today_checkins ? data.today_checkins.filter(c => c.checked).length : 0;
            document.getElementById('habit-count').textContent = checkedCount;
            document.getElementById('habit-detail').textContent = `总习惯数: ${data.total_habits || 0}`;
            
            // 显示今日习惯打卡
            const habitsContainer = document.getElementById('today-habits');
            if (data.today_checkins && data.today_checkins.length > 0) {
                const displayHabits = data.today_checkins.slice(0, 3);  // 最多显示3条
                const remainingCount = data.today_checkins.length - 3;
                
                habitsContainer.innerHTML = displayHabits.map(item => {
                    const habit = item.habit;
                    const checked = item.checked;
                    const progress = item.count || 0;
                    const target = habit.target_count || 1;
                    return `
                        <div class="mb-2 border-bottom pb-2">
                            <div class="d-flex justify-content-between align-items-center">
                                <span>${habit.icon || '📝'} ${habit.name}</span>
                                ${checked ? 
                                    `<span class="badge bg-success">✓ ${progress}/${target}</span>` :
                                    `<span class="badge bg-secondary">${progress}/${target}</span>`
                                }
                            </div>
                        </div>
                    `;
                }).join('') + (remainingCount > 0 ? `
                    <div class="text-center mt-2">
                        <small class="text-muted">还有 ${remainingCount} 个习惯...</small>
                    </div>
                ` : '');
            } else {
                habitsContainer.innerHTML = '<p class="text-muted text-center">暂无习惯追踪</p>';
            }
        })
        .catch(error => console.error('Error:', error));
    
    // 获取今日待办
    fetch('/todo/api/today')
        .then(response => response.json())
        .then(data => {
            const todosContainer = document.getElementById('today-todos');
            if (data.todos && data.todos.length > 0) {
                const displayTodos = data.todos.slice(0, 3);  // 最多显示3条
                const remainingCount = data.todos.length - 3;
                
                todosContainer.innerHTML = displayTodos.map(todo => `
                    <div class="mb-2 border-bottom pb-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong ${todo.completed ? 'class="text-decoration-line-through text-muted"' : ''}>${todo.title}</strong><br>
                                <small class="text-muted">${todo.category || '其他'}</small>
                            </div>
                            <span class="badge bg-${todo.priority === 'high' ? 'danger' : todo.priority === 'medium' ? 'warning' : 'secondary'}">${todo.priority}</span>
                        </div>
                    </div>
                `).join('') + (remainingCount > 0 ? `
                    <div class="text-center mt-2">
                        <small class="text-muted">还有 ${remainingCount} 条...</small>
                    </div>
                ` : '');
            } else {
                todosContainer.innerHTML = '<p class="text-muted text-center">今日暂无待办事项</p>';
            }
        })
        .catch(error => console.error('Error:', error));
    
    // 获取进行中的目标
    fetch('/goal/api/goals?status=进行中')
        .then(response => response.json())
        .then(data => {
            const goalsContainer = document.getElementById('active-goals');
            if (data.goals && data.goals.length > 0) {
                const displayGoals = data.goals.slice(0, 3);  // 最多显示3条
                const remainingCount = data.goals.length - 3;
                
                goalsContainer.innerHTML = displayGoals.map(goal => `
                    <div class="mb-3">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>${goal.title}</strong>
                            <span class="badge bg-primary">${goal.category}</span>
                        </div>
                        <div class="progress" style="height: 20px;">
                            <div class="progress-bar bg-success" role="progressbar" style="width: ${goal.progress}%">
                                ${goal.progress}%
                            </div>
                        </div>
                    </div>
                `).join('') + (remainingCount > 0 ? `
                    <div class="text-center mt-3">
                        <small class="text-muted">还有 ${remainingCount} 个目标...</small>
                    </div>
                ` : '');
            } else {
                goalsContainer.innerHTML = '<p class="text-muted text-center">暂无进行中的目标</p>';
            }
        })
        .catch(error => console.error('Error:', error));
});
</script>
{% endblock %}

